<?php 

namespace Cli\Controller;

use Think\Log;
use Cli\Event\CronEvent;
use Think\Upload\Driver\Ucloud;
use Api\Event\CacheEvent;

class CronController 
{

    private $serv;

    static $cronRegister = [
        [ 1000, 'videoplay'], // 每5分钟更新play
        // [ 100, 'test'], // 每5分钟更新play
    ];

    public function run()
    {
        $this->serv = new \swoole_server("127.0.0.1", 6061);
        $this->serv->set([
            'worker_num'      => 4,   //一般设置为服务器CPU数的1-4倍
            // 'daemonize' => true,  //以守护进程执行
            'reactor_num'     => 4,
            'max_request'     => 10000,
            'dispatch_mode'   => 2,
            'task_worker_num' => 4,  //task进程的数量
            "task_ipc_mode "  => 2,   
        ]);

        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }

    public function onStart( \swoole_server $serv) {
        echo 'Start..';
        $cronTable = [];
        $serv->tick(1000, function(){
            // Log::record("[swoole]");
            // Log::save();
            // echo 1;
        });
        // foreach (self::$cronRegister as $cron) {
        //     $cronTable[$cron[1]] = CronEvent::instance($cron[1]);
        //     if (!$cronTable[$cron[1]]){
        //         continue;
        //     }
        //     $cronEvent = $cronTable[$cron[1]];
        //     $serv->tick($cron[0], function() use($serv, $cronEvent)
        //     {
        //         $serv->task($cronEvent);
        //     });
        // }
    }

    public function onReceive( \swoole_server $serv, $fd, $from_id, $data ) {
        
    }

    public function onTask($serv, $task_id, $from_id, &$data) {
        $data->run();
    }
    
    public function onFinish($serv, $task_id, $data) {
        echo 'over';
    }

    public function getDateRangerVideo($time_ranger, &$videos)
    {
        $map['create_time'] = [
            'between', [  $time_ranger[0]  , $time_ranger[1] ]
        ];

        $map['status'] = 1;
        $map['type']   = 0;
        $map['race_id'] = array('egt', null);
        $videos = service('Video')->field('id,create_time,play')->where($map)->select();
    }

    // 随机点赞  每10分钟从里面找出随机的 昨天30个视频进行点赞/ 前一天的20个 / 再前一天的10个
    public function video_zan()
    {
        echo '[TASK] - [video_zan]:暂时取消点赞机器人功能';
        exit;
        $date = date('Y-m-d'); // 当天凌晨
        $datestr = strtotime($date);

        $maxs = [30, 20, 10];
        $daVideos = [];

        // 取昨日的数据
        $this->getDateRangerVideo([ $datestr - 1*24*3600  , $datestr ], $daVideos[0]);
        $this->getDateRangerVideo([ $datestr - 2*24*3600  , $datestr - 1*24*3600], $daVideos[1]);
        $this->getDateRangerVideo([ $datestr - 3*24*3600  , $datestr - 2*24*3600 ], $daVideos[2]);
        $likeServ = service('Like');
        $likeEvent = event('Like');
        // print_r($daVideos);
        foreach ($daVideos as $key => $videos) {
            $videos = array_values($videos);
            shuffle($videos);
            $videos = array_chunk($videos, $maxs[$key])[0];
            foreach ($videos as $video) {
                $videozan = $likeServ->countByVideo($video['id']);
                $max = ceil($video['play']/25);
                if ($videozan + 1 <= $max){
                    // if
                    $likeEvent->add(0, 0, $video['id'], $ret, ['from' => 'robot']);
                }
            }
        }
        \Think\Log::record("[TASK] - [video_zan]: run ok",'DEBUG');
        echo 'run ok';
        exit;
    }

    // 每分钟一次 对视频进行游客评论
    public function video_comment()
    {
        $config = api( 'Config/lists' );
        C( $config ); //添加配置
        $auto_comment_words = C('auto_comment_words');
        if(!$auto_comment_words){
            return;
        }

        $auto_comment_words = explode("\r\n", $auto_comment_words);

        $date = date('Y-m-d'); // 当天凌晨
        $datestr = strtotime($date);

        $daVideos = [];

        // 取3天内的数据
        $this->getDateRangerVideo([ $datestr - 3*24*3600  , NOW_TIME ], $daVideos);
        if (!$daVideos){
            echo 'run none';
            return;
        }
        $daVideos = array_values($daVideos);
        shuffle($daVideos);
        // 找出5个视频
        $video_ids = array_chunk($daVideos, 5)[0];

        // 发布评论
        foreach ($video_ids as $video) {

            $viedeoObj = event('Video')->detail($video['id']);
            if ($viedeoObj['statis']['comments'] >= $video['play']/50 ){
                continue;
            }

            event('Comments')->add($video['id'], ['uid' => 0], $auto_comment_words[rand(0, count($auto_comment_words) - 1)], $ret, ['from' => 'robot']);
        }
        \Think\Log::record("[TASK] - [video_comment]: run ok",'DEBUG');
        echo 'run ok';
        exit;
    }

    
    // 每5分钟一次 对视频进行加播放
    public function video_play()
    {
        $date = date('Y-m-d'); // 当天凌晨
        $datestr = time();//strtotime($date);
        $hour = date('H');
        if ($hour > 2 && $hour < 10){
            echo 'sleep time';
            exit;
        }

        // 找出5天内发布的视频
        $map['create_time'] = [
            'between', [  $datestr - 5*24*3600  , $datestr ]
        ];

        $map['status'] = 1;
        $map['type']   = 0;
        $map['race_id'] = array('egt', null);
        $vServ = service('Video');
        $videos = $vServ->field('id,create_time')->where($map)->select();
        $result = [];
        foreach ($videos as $video) {
            switch (  ceil(($datestr - $video['create_time'])/(24*3600) ) ) {
                case 1:
                    $range = [4,8];
                    break;
                case 2:
                    $range = [3,6];
                    break; 
                case 3:
                    $range = [2,4];
                    break;
                case 4:
                    $range = [1,3];
                    break;
                case 5:
                    $range = [1,2];
                    break;            
                default:
                    $range = [0,1];
                    break;
            }
            $addplay = mt_rand($range[0], $range[1]);
            if ($addplay > 0){
                $vServ->where(['id' => $video['id']])->setInc('play', $addplay);
                event('Statis')->inRank($video['id'], $addplay);
            }
        }

        // 从排行榜中拿出当天的数据  增加
        $topVides = event('Video')->getTop10();
        foreach ($topVides as $video_id => $play) {
            $video_id = (int)$video_id;
            if ($play > 0){
                $addplay = ceil($play / 100);
                $vServ->where(['id' => $video_id])->setInc('play', $addplay);
                event('Statis')->inRank($video_id, $addplay);
            }
        }

        \Think\Log::record("[TASK] - [video_play]: run ok",'DEBUG');
        echo 'run ok';
        exit;
    }
 

    // 记录昨日的统计情况
    public function daily_statis($date = '')
    {
        !$date && $date = date('Ymd', strtotime('-1 day'));
        if ($date == date('Ymd')){
            return;
        }
        // 把今天的数据存入
        $logServ = service('ImbaLog/LogSource');
        $map = [
            'object_type'  => 'user',
            'object_class' => 'login',
            'platform'     => "5",
        ];
            
        if ($logServ->table("imba_mac_daily_{$date}")->count() == 0){
            $pcmac = $logServ->table("imba_log_source_{$date}")->where($map)->select();
            $macs = [];
            foreach ($pcmac as $item) {
                if (!empty($item['extend']['mac'])){
                    $macs[$item['extend']['mac']] = 1;
                }
            }
            $macs = array_keys($macs);
            foreach ($macs as $mac) {
                $logServ->table("imba_mac_daily_{$date}")->add(['mac' => $mac]);
            }
        }
        
        $result = service('Statis/LogStatisItem')->getDailyData($date);
        echo 'ok';
        print_r($result);
    }

    // 初始化总的每日的mac
    // from 20160513
    public function mac_init()
    {
        $today = date('Ymd');
        $date = $from  = '20160601';
        do{
            echo $date,":\r\n";
            $this->daily_statis($date);
            $date = date('Ymd', strtotime($date." +1 day"));
        }while($date < $today);
        exit;
    }

    // 视频转码查询回调信息
    public function trancf_code_verify()
    {
        $map = [
            'dpi_videos' => ['neq', null],
            'type'       => 0,
            'id'         => ['gt', 19917],
        ];
        $model = service('Video');
        $videos = $model->where($map)->select();
        $Ucloud = new Ucloud(C('VIDEO_UPLOAD.rootPath'), C('UPLOAD_UCLOUD_VIDEO_CONFIG'));
        echo "begin..\r\n";
        foreach ($videos as $video) {
            echo "video: {$video['id']}: \r\n";
            if (!empty($video['dpi_videos'])){
                foreach ($video['dpi_videos'] as $dpi => $dpi_video) {
                    if ($dpi_video['status'] != 'ok' && !empty($dpi_video['taskid'])){
                        $taskid = $dpi_video['taskid'];
                        echo "task_id: {$taskid}:";
                        $result = $Ucloud->taskStatus($taskid);
                        // print_r($result);
                        if ($result['RetCode'] == 0 && $result['Status'] == 'finished'){
                            echo "ok";
                            $save['dpi_videos'][$dpi] = $dpi_video;
                            $save['dpi_videos'][$dpi]['uri'] = $result['DestFilePath'];
                            $save['dpi_videos'][$dpi]['status'] = 'ok';
                            $model->where(['id' => (int)$video['id']])->save($save);
                        }else{
                            echo "err";
                        }
                        echo "\r\n";
                    }else{
                        echo "finished\r\n";
                    }
                }
            }
            echo "video fishish\r\n";
        }
        echo  "over\r\n";
    }

    /**
     * 更新热门视频
     * @author liubo <liubo@ilongyuan.com.cn> 2016-06-27
     */
    public function update_hot_videos() {
        $Redis = CacheEvent::instance(0);
        load_config($Redis);
        unset($Redis);
        echo "update_hot_videos: begin\r\n";
        event('VideoHot')->setData();
        echo "update_hot_videos: finish\r\n";
    }

    /**
     * 处理错误的视频tag数据
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function update_video_tags() {
        $map = [
            'tags' => ['$regex' => 'tags']
        ];
        $model = service('Video');
        $videos = $model->where($map)->select();

        foreach ($videos as $video) {
            echo "video: {$video['id']}: \r\n";
            $tags = $video['tags'][0];
            $tags = explode('tags[]=', $tags);
            $model->where(['id' => (int)$video['id']])->save(['tags' => $tags]);
        }
        echo "success\r\n";
    }


    public function cndota()
    {
        $serv = service('Cndota/CndotaData');
        $tserv = service('Cndota/CndotaTeam');
        $teams = $tserv->getField('id', true);
        // print_r($teams);exit;
        $map = [
            'uid' => ['ne', null],
            'team_id' => ['ne', null]
        ];
        $lists = $serv->where($map)->select();
        foreach ($lists as $item) {
            $team[$item['team_id']] += 1;
        }
        print_r($team);
        $max = 10;
        $add = [
            'create_time' => time(),
            'uid'   => 999999
        ];
        foreach ($teams as $team_id) {
            $count = $team[$team_id];
            if ($count < 10){
                $add['team_id'] = (int)$team_id;
                for ($i = 0; $i < $max - $count; $i++){
                    $serv->add($add);
                    echo "add one\r\n";
                }
            }
        }
    }

    // 把oss地址转到ucloud
    public function ossuri()
    {
        $serv = service('Video');
        $map = [
            'uri' => ['like','66tv'],
        ];
        $lists = $serv->where($map)->select();
        print_r($lists);
        $search = 'http://static.66tv.tv';
        $search_len = strlen($search);
        foreach ($lists as $video) {
            $id = (int)$video['id'];
            $uri = $video['uri'];
            $pre_uri = $video['pre_uri'];
            $thumb = $video['thumb'];
            $save = [
                'id' => $id,
            ];
            if (startWith($uri, $search)){
                $uri = substr($uri, $search_len);
                $save['uri'] = $uri;
                // $serv->save($save);
            }
            if (startWith($pre_uri, $search)){
                $pre_uri = substr($pre_uri, $search_len);
                $save['pre_uri'] = $pre_uri;
                // $serv->save($save);
            }
            if (startWith($thumb, $search)){
                $thumb = substr($thumb, $search_len);
                $save['thumb'] = $thumb;
                // $serv->save($save);
            }
            if (count($save) > 1){
                $serv->save($save);
            }
        }
    }

    /**
     * 处理imba_video表zan字段的数据
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function update_video_zan()
    {
        $vService = service('Video');
        $lService = service('Like');
        $videos = $vService->select();

        foreach ($videos as $video) {
            echo "video: {$video['id']}: \r\n";
            $likeCount = $lService->where(['target_id' => $video['id'], 'type' => 0])->count();
            $vService->where(['id' => (int)$video['id']])->save(['zan' => (int)$likeCount]);
        }
        echo "success\r\n";
    }

    public function create_user() {
        $User = service('Users');

        for ($i=0; $i < 10; $i++) {
            $rand = rand(10000, 99999);
            $mobile = '19999'.$rand.$i;
            echo $mobile, "\r\n";
            $uid = $User->register($mobile, '123456', $mobile);
            echo "uid:{$uid}\r\n";
        }
        echo "finish";
    }

    // 手动转码
    public function manul_trancode()
    {
        $serv = service('Video');
        $event = event('Video');
        // $map  = [
        //     'dpi' => ['gt', '720'],
        //     'id'  => ['lt', 26270],
        // ];
        $map = [
            'dpi' => '540',
            'dpi_videos.720.status' => 'ok'
        ];
        $videos = $serv->where($map)->select();

        // echo count($videos);
        // print_r($videos);
        $transcode = [
            // 1920  1280  960  :  11:9
            '1080', '720', '540', '360'
        ];
        echo "begin trance code..\r\n";
        foreach ($videos as $video) {
            $dpi = $video['dpi'];
            $save = [
                'id'         => (int)$video['id'],
                'dpi_videos' => [],
            ];
            if ($dpi){
                echo "trance video ID: {$video['id']}_ \r\n";
            // 设置转码集合
                foreach ($transcode as $value) {
                    if ($dpi > $value){
                        $taskId = $event->transcodeDpi($video, $value);
                        $save['dpi_videos'][$value]['taskid'] = $taskId;
                        echo "dpi {$value}, taskId: {$taskId}\r\n";
                    }
                }

                $res = $serv->save($save);
                echo "trance save: ". ($res ? 'ok':'err') . "\r\n";
            }
            echo  "trance video ID: {$video['id']} over...\r\n";
        }
        echo "trance over...\r\n";
    }

    public function update_resource()
    {
        $data = service('ResourceGroup')->field('id,pub_time')->select();
        foreach ($data as $key => $value) {
            $value['pub_time'] = floatval($value['pub_time']);
            service('ResourceGroup')->save($value);
            echo "SUCCESS:{$value['id']}\r\n";
        }
        echo "FINISH\r\n";
    }

    public function resource_store($type = '')
    {
        switch ($type) {
            case 'video':
                $videos = service('video')->select();
                foreach ($videos as $video) {
                    $video_resource = [
                        'object_type' => 0, // 视频类型
                        'object_id'   => $video['id'], // 视频id
                        'uid'         => $video['uid'], // 用户id
                        'game_id'     => $video['game_id'], // 游戏id
                        'pub_time'    => "{$video['create_time']}.{$video['id']}0", // 时间.id.type 排序用
                        'object'      => [], // 资源信息
                        'status'      => $video['status'],
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    try {
                        $res = service('ResourceGroup')->add($video_resource);
                        echo "SUCCESS:ID-{$res},VID-{$video['id']}\r\n";
                    } catch(\Exception $e) {
                        echo "FAIL:duplicate key error,VID-{$video['id']}\r\n";
                    }
                }
                echo 'FINISH'."\r\n";
                break;
            case 'match':
                $races = service('RaceGroup')->select();
                foreach ($races as $race) {
                    $time = strtotime($race['race_time']);
                    $status = 0;
                    if (!empty($race['state']) && !empty($race['status']) && $race['status'] > 0) {
                        $status = 1;
                    }
                    $race_resource = [
                        'object_type' => 1,
                        'object_id'   => $race['id'],
                        'uid'         => 0,
                        'game_id'     => $race['game_id'], // 游戏id
                        'pub_time'    => "{$time}.{$race['id']}1", // 时间.id.type 排序用
                        'object'      => [], // 资源信息
                        'status'      => $status,
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    try {
                        $res = service('ResourceGroup')->add($race_resource);
                        echo "SUCCESS:ID-{$res},RID-{$race['id']}\r\n";
                    } catch(\Exception $e) {
                        echo "FAIL:duplicate key error,RID-{$race['id']}\r\n";
                    }
                }
                echo 'FINISH'."\r\n";
                break;
            case 'news':
                $newslist = service('news')->where(['type' => 0])->select();
                foreach ($newslist as $news) {
                    $news_resource = [
                        'object_type' => 2,
                        'object_id'   => $news['id'],
                        'uid'         => 0,
                        'game_id'     => $news['game_id'], // 游戏id
                        'pub_time'    => "{$news['create_time']}.{$news['id']}2", // 时间.id.type 排序用
                        'object'      => [], // 资源信息
                        'status'      => $news['status'],
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    try {
                        $res = service('ResourceGroup')->add($news_resource);
                        echo "SUCCESS:ID-{$res},NID-{$news['id']}\r\n";
                    } catch(\Exception $e) {
                        echo "FAIL:duplicate key error,NID-{$race['id']}\r\n";
                    }
                }
                echo 'FINISH'."\r\n";
                break;
        }
    }
}